import fs from 'fs-extra';
import { SVNClient } from '@taiyosen/easy-svn';
import { ToolEnv } from '../typings';
import { toolchain } from '../tools/toolchain.js';

export class SvnHolder {
    public svnClient = new SVNClient();

    private static ins: SvnHolder;
    public static get Instance(): SvnHolder {
        if(!SvnHolder.ins) SvnHolder.ins = new SvnHolder();
        return SvnHolder.ins;
    }

    private commitOutput: string = '';

    constructor() {
        const env = process.env as unknown as ToolEnv;
        if(env.SVN_USERNAME && env.SVN_PASSWORD) {
            this.svnClient.setConfig({
                username: env.SVN_USERNAME, 
                password: env.SVN_PASSWORD, 
                globalParams: ['--non-interactive', '--trust-server-cert', '--no-auth-cache']
            });
        }
    }

    public async checkSVN(revert: boolean, localPath: string, svnPath: string | string[]): Promise<void> {
        if(fs.existsSync(localPath)) {
            await this.svnClient.cleanup(true, localPath);
            if (revert) {
                await this.svnClient.revert(localPath);
            }
            await this.svnClient.update(localPath);
        } else {
            await fs.mkdirp(localPath);
            await this.svnClient.checkout(svnPath, localPath);
        }
    }

    public async commitSVN(msg: string, ...paths: string[]): Promise<void> {
        await this.svnClient.addUnversioned(...paths);
        this.commitOutput = await this.svnClient.commit(msg, ...paths);
    }

    public getLastCommitFiles(): string[] {
        const files: string[] = [];
        const mchs = this.commitOutput.matchAll(/Sending\s+(\S+)/g);
        for (const mch of mchs) {
            files.push(mch[1]);
        }
        return files;
    }
}

export function adjustSVN(raw: string) {
    if (toolchain.options.publish) {
        raw = raw.replace('trunk', 'branches/publish')
    }
    return raw;
}
